using System;
using System.Collections.Generic;
using System.Text;
using TaugeLibrary.Classes;
using System.Data.SqlClient;
using System.Data;

namespace TaugeFramework.Classes
{

    class DatabaseUpdater
    {
        #region memvar
        private Database m_db;
        private int m_version;
        private string m_id;
        private string m_prev_error_list;
        #endregion

        #region event
        public event GeneralEventHandler Progress;
        protected virtual void onProgress(GeneralEventArgs e)
        {
            if (Progress != null)
                Progress(this, e);
        }
        #endregion

        #region properties
        public int Version
        {
            get { return m_version; }
        }
        public string ID
        {
            get { return m_id; }
        }
        public string PreviousErrorList
        {
            get { return m_prev_error_list; }
        }
        #endregion

        #region constructor
        public DatabaseUpdater(Database p_db)
        {
            m_db = p_db;
            loadInfo();
        }
        #endregion


        #region method

        public void loadInfo()
        {
            SqlDataReader sdr = m_db.executeReader("SELECT TOP 1 * FROM sysobjects WHERE Name='DBInfo' AND xtype='U'");
            if (!sdr.Read())
            {
                m_db.executeNonQuery("CREATE TABLE [dbo].[DBInfo] ( [DBVersion] [int] , [DBID] [varchar] (50)  ) ");
                m_db.executeNonQuery("INSERT INTO DBInfo VALUES (0,'DEFAULT')");
                m_db.executeNonQuery("CREATE TABLE [dbo].[DBUPErr] ( [DBVersion] [int] ,	[Statement] [varchar] (8000) , [Comment] [varchar] (2000) )");
            }
            sdr.Close();
            sdr = null;

            sdr = m_db.executeReader("SELECT TOP 1 * FROM DBInfo");
            if (sdr.Read())
            {
                m_version = (int)sdr["DBVersion"];
                m_id = sdr["DBID"].ToString();
            }
            else
            {
                m_version = 0;
                m_id = "NONE";
            }
            sdr.Close();
            sdr = null;

            m_prev_error_list = "";
            sdr = m_db.executeReader("SELECT * FROM DBUPErr ORDER BY DBVersion");
            while (sdr.Read())
                m_prev_error_list += sdr["DBVersion"].ToString() + ",";
            m_prev_error_list += "0";
            sdr.Close();
            sdr = null;
        }


        public void Update_XML(string p_UpdatePath, string p_filename)
        {
            loadInfo();
            string csql;
            if (p_UpdatePath == "")
                p_UpdatePath = Program.AppPath;
            if (p_filename == "")
                p_filename = "DBUP.XML";

            //read xml
            DataSet ds = new DataSet();
            ds.ReadXml(p_UpdatePath + @"\" + p_filename);

            if (ds.Tables.Count <= 0)
                return;

            onProgress(new GeneralEventArgs(0, "START", true, DateTime.Now));


            string cfilter = "";
            string[] apreverrorlist = m_prev_error_list.Split(',');

            for (int i = 0; i < apreverrorlist.Length; i++)
                cfilter += " OR dbver=" + apreverrorlist[i];



            DataRow[] adr = ds.Tables[0].Select(" dbver>" + LibConstants.sqlNum(m_version) + cfilter, "dbver");

            foreach (DataRow dr in adr)
            {
                if (((dr["incdb"].ToString().Trim() == "") || ((dr["incdb"].ToString() + "|").IndexOf(m_id) >= 0)) &&
                    ((dr["excdb"].ToString().Trim() == "") || ((dr["excdb"].ToString() + "|").IndexOf(m_id) < 0)))
                {
                    onProgress(new GeneralEventArgs(Convert.ToInt32(dr["dbver"]), dr["comment"].ToString(), true, DateTime.Now));
                    csql = LibConstants.txt2String(p_UpdatePath + @"\" + dr["fname"].ToString());
                    try
                    {
                        m_db.executeNonQuery(csql);
                        m_db.executeNonQuery("DELETE DBUPErr WHERE DBVersion=" + LibConstants.sqlNum(Convert.ToInt32(dr["dbver"])));
                        if (m_version < Convert.ToInt32(dr["dbver"]))
                            m_db.executeNonQuery("UPDATE DBInfo SET DBVersion=" + LibConstants.sqlNum(Convert.ToInt32(dr["dbver"])));
                        onProgress(new GeneralEventArgs(Convert.ToInt32(dr["dbver"]), "Update Succeeded", true, DateTime.Now));
                    }
                    catch (Exception ex)
                    {
                        m_db.executeNonQuery("INSERT INTO DBUPErr (dbversion, statement, comment) VALUES ( " + LibConstants.sqlNum(Convert.ToInt32(dr["dbver"])) + "," + LibConstants.sqlStr(csql) + "," + LibConstants.sqlStr(ex.Message) + ")");
                        onProgress(new GeneralEventArgs(Convert.ToInt32(dr["dbver"]), ex.Message, false, DateTime.Now));
                    }

                }
            }

            onProgress(new GeneralEventArgs(0, "FINISH", true, DateTime.Now));
        }

        #endregion
    }
}
